﻿using BaseUI;
using BLL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.UI.WebControls;

namespace Thksoft.BusinessExpansion.Process
{
    public partial class QueueSelect : BasePage
    {
        private Lc_QueueBLL lqb = new Lc_QueueBLL();
        private Lc_NodeBLL lnb = new Lc_NodeBLL();
        private Lc_ProcessBLL lpb = new Lc_ProcessBLL();

        private Lc_BlockBLL lbb = new Lc_BlockBLL();
        private Sys_UserBLL sub = new Sys_UserBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindProcess();
                BindCompany();
                if (Session["QueBufferMemory1"] != null)
                {
                    ddlProcess.SelectedValue = Session["QueBufferMemory1"].ToString();
                }

                if (Session["QueBufferMemory3"] != null)
                {
                    ddlCheckType.SelectedValue = Session["QueBufferMemory3"].ToString();
                }

                ViewState["SortOrder"] = "N_QUEUE_NUMBER";
                ViewState["OrderDire"] = " asc ";

                Bind();
            }
        }

        private void BindCompany()
        {
            DataTable tableOrganization = new Sys_CompanyBLL().SelectByWhere("", lognUser.USER_COMPANY.ToString());
            if (tableOrganization != null && tableOrganization.Rows.Count > 0)
            {
                // setList(tableOrganization, ddlCompany);
                PublicMethod.BindDDL(ddlCompany, tableOrganization, "CMY_ID", "CMY_NAME", false);

                ddlCompany.Items.Insert(0, new ListItem("通用", "0"));

                ddlCompany.SelectedValue = "0";
            }
            else
            {
                ddlCompany.Items.Add(new ListItem("无", "0"));
            }
        }

        private void BindProcess()
        {
            //查询有效流程
            var allprocess = lpb.GetProcByState(" and n_process_state=1 ", lognUser.USER_NAME);
            ddlProcess.DataSource = allprocess;
            ddlProcess.DataTextField = "C_PROCESS_NAME";
            ddlProcess.DataValueField = "N_PROCESS_ID";
            ddlProcess.DataBind();
            ddlProcess.Items.Insert(0, new ListItem("---请选择---", "-1"));

            if (Session["QueBufferMemory1"] != null)
            {
                ddlProcess.SelectedValue = Session["QueBufferMemory1"].ToString();
            }
        }

        private void Bind()
        {
            string whereStr = "";
            if (ddlProcess.SelectedValue != "-1")
            {
                whereStr += " AND lcp.N_PROCESS_ID=" + ddlProcess.SelectedValue;
            }

            if (ddlCheckType.SelectedIndex != 0)
            {
                whereStr += " AND lcq.N_AUDIT_TYPE=" + ddlCheckType.SelectedValue;
            }

            if (ddlCompany.SelectedValue != "-1")
            {
                whereStr += " AND lcq.N_COMPANYID=" + ddlCompany.SelectedValue;
            }

            ViewState["Where"] = whereStr;

            BindData(true);
        }

        protected void grvShow1_Sorting(object sender, GridViewSortEventArgs e)
        {
            //点击排序
            string sPage = e.SortExpression;

            if (sPage == "")
            {
                return;
            }
            if (ViewState["SortOrder"].ToString() == sPage)
            {
                if (ViewState["OrderDire"].ToString() == "Desc")
                    ViewState["OrderDire"] = "ASC";
                else
                    ViewState["OrderDire"] = "Desc";
            }
            else
            {
                ViewState["SortOrder"] = e.SortExpression;
                ViewState["OrderDire"] = "ASC";
            }

            BindData(false);
        }

        private void BindData(bool isFirst)
        {
            string Where = "";
            try
            {
                Where = ViewState["Where"].ToString();
            }
            catch
            {
                Where = "";
            }

            int rowcount = 0;
            if (isFirst)
            {
                PageIng.CurrentPage = 1;
            }
            rowcount = lqb.GetRecordCount(Where, lognUser.USER_NAME);

            /*重新构建DataTable 用于绑定视图
             *
             * @QueueID 队列ID
             * @ProcessName 流程名称
             * @NodeName 节点名称
             * @QueueNumber 执行序号
             * @TranTypeString 办理方式
             * @AududitTypeString 审核方式
             * @TransactionUserString 办理人员
             * @QueueModuleString 可见模板
             * @SpicalTable 关联表
             * @SpicalColunm 关联字段
             */
            DataTable viewTable = new DataTable();
            viewTable.Columns.Add("QueueID");
            viewTable.Columns.Add("ProcessName");
            viewTable.Columns.Add("NodeName");
            viewTable.Columns.Add("QueueNumber");
            viewTable.Columns.Add("TranTypeString");
            viewTable.Columns.Add("AududitTypeString");
            viewTable.Columns.Add("TransactionUserString");
            viewTable.Columns.Add("QueueModuleString");
            viewTable.Columns.Add("SpicalTable");
            viewTable.Columns.Add("SpicalColunm");
            viewTable.Columns.Add("PostString");
            // DataSet dtItem;
            //  dtItem = lqb.GetListByPage(Where, "N_QUEUE_NUMBER ASC", PageIng.CurrentPage, PageIng.RowsPerPage);

            string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"];

            DataTable dt = lqb.GetListByPage(Where, sort, PageIng.CurrentPage, PageIng.RowsPerPage);
            var userids = new List<string>();
            var moduleids = new List<string>();
            var postids = new List<string>();
            foreach (DataRow item in dt.Rows)
            {
                if (item["C_QUEUE_TRANSACTION_ID"] != DBNull.Value)
                {
                    //办理人员ID
                    foreach (var itm in item["C_QUEUE_TRANSACTION_ID"].ToString().Split(','))
                    {
                        if (itm.Trim() != "")
                        {
                            userids.Add(itm);
                        }
                    }
                }
                if (item["C_QUEUE_BLOCK"] != DBNull.Value)
                {
                    foreach (var itm in item["C_QUEUE_BLOCK"].ToString().Split(','))
                    {
                        if (itm.Trim() != "")
                        {
                            moduleids.Add(itm);
                        }
                    }
                }
                if (item["C_POSTS"] != DBNull.Value)
                {
                    foreach (var itm in item["C_POSTS"].ToString().Split(','))
                    {
                        if (itm.Trim() != "")
                        {
                            postids.Add(itm);
                        }
                    }
                }
            }

            var users = sub.GetUsers(userids.Distinct().ToArray());//( new List<Sys_User>();
            var modules = lbb.GetByID(moduleids.Distinct().ToArray());// new List<Lc_Block>();
            //绑定视图模型
            foreach (DataRow item in dt.Rows)
            {
                var row = viewTable.NewRow();
                row["QueueID"] = item["N_QUEUE_ID"];
                row["ProcessName"] = item["C_PROCESS_NAME"];
                row["NodeName"] = item["C_NODE_NAME"];
                row["QueueNumber"] = item["N_QUEUE_NUMBER"];

                #region 方式

                int? tranType;
                if (item["N_TRAN_TYPE"] == DBNull.Value)
                {
                    tranType = null;
                }
                else
                {
                    tranType = Convert.ToInt32(item["N_TRAN_TYPE"]);
                }

                #endregion 方式

                row["TranTypeString"] = (tranType == null || tranType == 0) ? "人员办理" : "岗位办理";
                row["AududitTypeString"] = item["N_AUDIT_TYPE"];

                #region 获取添加用户

                var str = "";
                if (item["C_QUEUE_TRANSACTION_ID"] != DBNull.Value)
                {
                    foreach (var itm in item["C_QUEUE_TRANSACTION_ID"].ToString().Split(','))
                    {
                        if (itm.Trim() != "")
                        {
                            var user = users.FirstOrDefault(a => a.USER_ID == decimal.Parse(itm));
                            if (user != null)
                            {
                                str += user.USER_NAME + ",";
                            }
                        }
                    }
                    if (str != "")
                    {
                        str = str.Substring(0, str.Length - 1);
                    }
                }

                #endregion 获取添加用户

                row["TransactionUserString"] = str;

                #region 获取模板

                str = "";
                if (item["C_QUEUE_BLOCK"] != DBNull.Value)
                {
                    foreach (var itm in item["C_QUEUE_BLOCK"].ToString().Split(','))
                    {
                        if (itm.Trim() != "")
                        {
                            var user = modules.FirstOrDefault(a => a.N_BLOCK_ID == decimal.Parse(itm));
                            if (user != null)
                            {
                                str += user.C_BLOCK_NAME + ",";
                            }
                        }
                    }
                    if (str != "")
                    {
                        str = str.Substring(0, str.Length - 1);
                    }
                }

                #endregion 获取模板

                row["QueueModuleString"] = str;
                row["SpicalTable"] = item["C_SPICAL_TABLE"];
                row["SpicalColunm"] = item["C_SPICAL_COL"];
                /*代码后续接着完成*/

                string pots = GetRoleNames(item["C_POSTS"].ToString());

                row["PostString"] = pots;
                viewTable.Rows.Add(row);
            }

            if (viewTable.Rows.Count > 0)
            {
                PageIng.Visible = true;
                PageIng.RowsCount = rowcount;
                PageIng.DataSource = viewTable;
                PageIng.GridViewSource = grvShow1;
                PageIng.RowsPerPage = PageIng._rowsPerPage;
                PageIng.Bind();
            }
            else
            {
                PageIng.DataSource = dt;
                PageIng.GridViewSource = grvShow1;
                grvShow1.DataSource = null;
                grvShow1.DataBind();
                PageIng.Visible = false;
            }
        }

        protected void btnSelect_Click(object sender, EventArgs e)
        {
            Bind();
        }

        protected void btnInsert_Click(object sender, EventArgs e)
        {
            Session["QueBufferMemory1"] = ddlProcess.SelectedValue.ToString();

            Session["QueBufferMemory3"] = ddlCheckType.SelectedValue.ToString();
            MessageBox.ResponseScript(this, "FORM_INSERT();");
            //Response.Redirect("QueueEdit.aspx");
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            int count = 0;
            for (int i = 0; i < grvShow1.Rows.Count; i++)
            {
                if (((CheckBox)grvShow1.Rows[i].FindControl("chkSelectId")).Checked == true)
                {
                    count++;
                    if (count == 1)
                    {
                        Session["QueBufferMemory1"] = ddlProcess.SelectedValue.ToString();

                        Session["QueBufferMemory3"] = ddlCheckType.SelectedValue.ToString();

                        string pid = ((CheckBox)grvShow1.Rows[i].FindControl("chkSelectId")).ToolTip;
                        MessageBox.ResponseScript(this, "FORM_EDIT(\"" + pid + "\");");

                        //string url = "QueueEdit.aspx?ID=" + pid;
                        //Response.Redirect(url);
                        return;
                    }
                }
            }
        }

        protected void PageIng_DataBinding(object sender, EventArgs e)
        {
            BindData(false);
        }
    }
}